package com.demo.crm.springboot3security.service.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;

import com.demo.crm.springboot3security.entity.Permission;
import com.demo.crm.springboot3security.mapper.PermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.demo.crm.springboot3security.entity.Role;
import com.demo.crm.springboot3security.mapper.RoleMapper;
import com.demo.crm.springboot3security.service.RoleService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public Role findByName(String name) {
        return roleMapper.findByName(name);
    }

    @Override
    @Transactional
    public Role save(Role role) {
        if (role.getId() == null) {
            roleMapper.insert(role);
        } else {
            roleMapper.update(role);
        }
        return role;
    }

    @Override
    @Transactional
    public void delete(Long id) {
        roleMapper.deleteById(id);
    }

    @Override
    public Role findById(Long id) {
        return roleMapper.selectOneById(id);
    }

    @Override
    public List<Role> findAll() {
        return roleMapper.selectAll();
    }

    @Override
    public Page<Role> findByPage(int pageNumber, int pageSize) {
        return roleMapper.paginate(pageNumber, pageSize, QueryWrapper.create());
    }

    @Override
    public boolean existsByName(String name) {
        QueryWrapper query = QueryWrapper.create().where("name = ?", name);
        return roleMapper.selectCountByQuery(query) > 0;
    }

    @Override
    @Transactional
    public void assignPermissions(Long roleId, Set<Long> permissionIds) {
        Role role = Optional.ofNullable(roleMapper.selectOneById(roleId))
                .orElseThrow(() -> new RuntimeException("角色不存在"));
        Set<Permission> permissions = new HashSet<>(permissionMapper.selectListByIds(permissionIds));
        role.setPermissions(permissions);
        roleMapper.update(role);
    }
}